/**
 * 
 */
package com.theunderminejournal.updater;

import java.io.File;
import java.util.Date;

import com.theunderminejournal.updater.gui.TUJGUI;

/**
 * 
 *
 */
public class TUJMarketDataThread implements Runnable {

	private TUJMarketData tujMarketData;
	
	private PropertiesUtil propertiesUtil;
		
	private boolean running = true;
	
	private TUJGUI tujgui;
	
	public TUJMarketDataThread(TUJGUI tujgui){
		super();
		
		tujMarketData = new TUJMarketData();
		propertiesUtil = new PropertiesUtil();
		
		this.tujgui = tujgui;
		
	}
	
	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	public void run() {
		while(running){
			//
			propertiesUtil.loadProperties();
			
			if(propertiesUtil.getMarketDataFile() != null && propertiesUtil.getTujUrl() != null){
				Date currentDate = new Date();
				
				if(currentDate.getTime() > propertiesUtil.getNextUpdate()){
					
					//Set LastUpdate
					Long lastUpdate = currentDate.getTime();
					propertiesUtil.setLastUpdate(lastUpdate);
					
					//Store
					propertiesUtil.storeProperties();
					
					//Update GUI
					tujgui.getLastUpdateTimeLabel().setText(new Date(lastUpdate).toString());
					tujgui.getNextUpdateTimeLabel().setText(new Date(propertiesUtil.getNextUpdate()).toString());
					
					tujMarketData.updateMarketData(new File(propertiesUtil.getMarketDataFile()), propertiesUtil.getTujUrl());
				}
				
				
				
			}
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}
		}

	}

	/**
	 * @return the running
	 */
	public boolean isRunning() {
		return running;
	}

	/**
	 * @param running the running to set
	 */
	public void setRunning(boolean running) {
		this.running = running;
	}

	
}
